package com.alibaba.system.service.impl;

import com.alibaba.basic.service.impl.BaseServiceImpl;
import com.alibaba.system.domain.Menu;
import com.alibaba.system.mapper.MenuMapper;
import com.alibaba.system.service.IMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 业务实现类：
 */
@Service
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements IMenuService {

    @Autowired
    private MenuMapper menuMapper;


// 查询菜单树
    @Override
    public List<Menu> menuTree() {

        List<Menu> menus = menuMapper.findAll();
        // 创建一个map集合
        HashMap<Long, Menu> map = new HashMap<>();
        for (Menu menu : menus) {
            map.put(menu.getId(),menu);
        }
        List<Menu> menuTree = new ArrayList<>();
        for (Menu menu : menus) {
           if (menu.getParentId()==null){
               menuTree.add(menu);

           }else {
               // 当前菜单的父id
               Long parentId = menu.getParentId();
               Menu prentMenu = map.get(parentId);
               if (prentMenu!=null){
                   prentMenu.getChildren().add(menu);
               }
           }
        }
        return menuTree;
    }
}
